﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Smatime.Web.DAO.SmatimeDatasetTableAdapters;
using Smatime.Web.Models;
using System.Data;

namespace Smatime.Web.DAO
{
    public class UserStroreMainRepository : BaseRepository<UserStore, SmatimeDataset.UserStoreDataTable, UserStoreTableAdapter>
    {
        /// <summary>
        ///     Get all stores belong to a User by the User id number.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<UserStore> GetStoresByUserId(long CompanyUserId)
        {
            using (var adapter = new UserStoreTableAdapter())
            {
                using (var table = adapter.GetStoreIdBy(CompanyUserId))
                {
                    var results = new List<UserStore>();
                    foreach (DataRow row in table.Rows)
                    {
                        var storeOfStaff = new UserStore();
                        storeOfStaff.FromDataRow(row);
                        results.Add(storeOfStaff);
                    }
                    return results;
                }
            }
        }
        public void UpdateStoreListByUser(long companyUserId, long[] storeIds)
        {
            using (var adapter = new UserStoreTableAdapter())
            {
                using (var userStoreTable = adapter.GetStoreIdBy(companyUserId))
                {
                    //Delete all rows that not exist on storeIds array
                    var allRows = userStoreTable.Rows.Cast<SmatimeDataset.UserStoreRow>();
                    foreach (var row in allRows)
                    {
                        if (!storeIds.Contains(row.CompanyStoreId))
                            row.Delete();
                    }

                    //Add all staff-store pairs that not exist in the table
                    foreach (var storeId in storeIds)
                    {
                        var userStoreRows = userStoreTable.Select(string.Format("CompanyUserId={0} and CompanyStoreId={1}", companyUserId, storeId));
                        if (userStoreRows == null || userStoreRows.Length == 0)
                        {
                            userStoreTable.AddUserStoreRow(companyUserId, storeId);
                        }
                    }

                    adapter.Update(userStoreTable);
                }
            }
        }
    }
}